package main

import (
	"context"
	"fmt"
	"gopkg.in/natefinch/lumberjack.v2"
	"log"
	"meeting-manager/global"
	"meeting-manager/internal/service"
	"meeting-manager/pkg/logger"
	"meeting-manager/pkg/setting"
	"net/http"
	"time"
)

func init() {
	// 读取配置文件
	err := setupSetting()
	if err != nil {
		log.Fatalf("init.setupSetting err: %v", err)
	}

	// 启动日志写入程序
	err = setupLogger()
	if err != nil {
		log.Fatalf("init.setupLogger err: %v", err)
	}
}

func main() {
	// 向注册中心发送注册请求
	err := service.Connect()
	if err != nil {
		fmt.Println(err)
		return
	}

	http.Handle("/register", &service.RegisterHandler{})
	http.Handle("/create", &service.CreateMeetingHandler{})
	http.Handle("/join", &service.JoinMeetingHandler{})
	http.Handle("/end", &service.EndMeetingHandler{})
	http.Handle("/heartbeat", &service.HeartbeatHandler{})

	s := &http.Server{
		Addr:           ":" + global.ServerSetting.Port,
		ReadTimeout:    global.ServerSetting.ReadTimeout * time.Second,
		WriteTimeout:   global.ServerSetting.WriteTimeout * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 发送错误时，服务终止
	go func() {
		log.Println(s.ListenAndServe())
		cancel()
	}()

	// 手动终止服务
	go func() {
		fmt.Println("Service meeting-manager started. Press any key to stop.")
		var str string
		_, _ = fmt.Scanln(&str)
		_ = s.Shutdown(ctx)
		cancel()
	}()

	<-ctx.Done()
	fmt.Println("Shutting down service")

}

// 读取配置文件
func setupSetting() error {
	s, err := setting.NewSetting()
	if err != nil {
		return err
	}

	err = s.ReadSection("Server", &global.ServerSetting)
	if err != nil {
		return err
	}

	err = s.ReadSection("Logger", &global.LoggerSetting)
	if err != nil {
		return err
	}

	err = s.ReadSection("RegistrationCenter", &global.RegistrationCenter)
	if err != nil {
		return err
	}

	return nil
}

// 启动日志写入程序
func setupLogger() error {
	fileName := global.LoggerSetting.SavePath + "/" +
		global.LoggerSetting.FileName + global.LoggerSetting.FileExt

	global.Logger = logger.NewLogger(&lumberjack.Logger{
		Filename:  fileName,
		MaxSize:   600,
		MaxAge:    10,
		LocalTime: true,
	}, "", log.LstdFlags).WithCaller(2)

	return nil
}
